# -*-coding:gbk-*-
# ProjectName: smart-meter-iot-test-console
# FileName: reportTask.py
# @DateTime :2023/4/7 23:46
# @Author :
# @Description:��ʱ�ϱ�����
from time import sleep, time
from common.util.configUtil.configUtil import ConfigUtil
from common.util.jsonUtl.jsonUtil import JsonUtil
from common.util.logUtil.logUtil import LoggerUtil
from common.util.mySqlUtil.mySqlPool import select_sql
from common.util.timeUtil.timeUtil import get_now_time
from core.mqtt.connect.mqtt import mqtt_connect, on_publish
from core.mqtt.libProject.reportData.reportData import packge_report_data_body

read_json = JsonUtil()
config = ConfigUtil()
deviceName = config.get_mqtt_config("deviceName")
client = mqtt_connect(deviceName)
logger = LoggerUtil()


def report() -> None:
    """
    :return:
    """
    try:
        client.loop_start()
        sleep(1)
        log_record()
        # ��ѯˮ�����µ���ˮ��
        selectUseTotal = read_json.read_sql("useTotal").format(deviceName)
        dbDataList = select_sql(sql=selectUseTotal, logType=1)
        count = 1
        for i in dbDataList:
            if count % 15 == 0:
                print(f"����:{count}")
                logger.debug(f"����:{count}")
                sleep(0.5)
            reporData = packge_report_data_body(i[0], i[1])
            topic = f"/sys/{config.get_productkey()}/{deviceName}/thing/event/property/post"
            on_publish(client, topic, str(reporData), 0)
            logger.info(f"�ϱ�����:\n{str(reporData)}")
            count += 1
        log_record(2)
    except Exception as e:
        raise e


def log_record(status: int = 1):
    statusContent = ""
    if status == 1:
        statusContent = "��ʼ"
    else:
        statusContent = "����"
    print(f"�ϱ�{statusContent}ʱ��:{get_now_time(1)}")
    logger.info(f"�ϱ�{statusContent}ʱ��:{get_now_time(1)}")
    logger.debug(f"�ϱ�{statusContent}ʱ��:{get_now_time(1)}")


def report_task() -> None:
    """
    :��ʱ�ϱ���ÿ��30���ϱ�һ��:
    """
    while True:
        report()
        sleep(5)


if __name__ == '__main__':
    report()
